<template>
	<div style="padding-bottom: 120px;">
		<van-sticky>
			<div class="searchBox">
				<div class="title">投放地址</div>
				<van-search v-model="params.storeName" placeholder="请输入店铺名称搜索" @search="handleSearch">
					<template #right-icon>
						<div class="search-confirm" @click.stop="handleSearch">
							<span style="margin-right: 10px;height: 24px;">|</span>
							<span class="search-text">搜索</span>
						</div>
					</template>
				</van-search>
			</div>
		</van-sticky>
		<van-pull-refresh v-model="refreshing" @refresh="onRefresh">
			<van-list v-model:loading="loading" v-model:error="error" error-text="请求失败，点击重新加载" :finished="finished"
				finished-text="没有更多数据了" @load="getdata">
				<!-- <DeviceList :list="list" :mark="mark" @AddressDelete="deletes" @AddressEdit="edit"></DeviceList> -->
				<div style="padding: 0 10px;">
					<div class="grid-content"  v-for="(item, index) in list" :key="index">
						<div style="padding: 10px;">
							<div class="flexbetween margin-b-12">
								<span class="storeTitle" style="width: 70%;">店铺：{{ item.storeName }}</span>
								<van-tag type="success" size="large" v-if="item.defaultFlag==0">默认地址</van-tag>
							</div>
							<p class="margin-t-0 margin-b-12">
								<span class="storeZi">
									详细地址：{{`${ item.province }` + `${ item.city }` + `${ item.district }` + `${ item.detailedAddress }`}}
								</span>
							</p>
							<div class="flexbetween">
								<p class="margin-t-0 margin-b-0">
									<span class="storeZi">
										店铺类型：{{ item.storeType }}
									</span>
								</p>
								<p class="margin-t-0 margin-b-0">
									<span class="storeZi">
										创建时间：{{ item.createTime }}
									</span>
								</p>
							</div>
						</div>
						<div class="divider"></div>
						<div class="grid-content-bottom">
							<p @click="edit(item)">编辑</p>
							<span style="color: #c1c5cd">|</span>
							<p @click="deletes(item)">删除</p>
						</div>
					</div>
				</div>
			</van-list>
		</van-pull-refresh>
		<!-- 新增地址 -->
		<div class="footer">
			<!-- <button class="addAddress" @click="addAddress">新增地址</button> -->
			<van-button round block type="primary" @click="addAddress" style="width: 80%;">
				新增地址
			</van-button>
		</div>

		<!-- 弹窗 -->
		<van-dialog v-model:show="dialogshow" title="提示" show-cancel-button @confirm="dialogConfirm"
			:keyboard-enabled="false">
			<div class="prompt">确定要删除该设备吗?</div>
		</van-dialog>
	</div>
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive
	} from "vue";
	import {
		deviceStoresList,
		deleteStore
	} from '@/api/deviceStores';
	import {
		getUserid,
		getIdentity
	} from '@/utils/auth';

	import {
		useRouter
	} from 'vue-router';
	import {
		showToast
	} from 'vant';
	const router = useRouter();


	onMounted(() => {
		getdata();
	});


	const deleteParmams = ref();
	const loading = ref(false);
	const finished = ref(false);
	const error = ref(false);
	// 下拉刷新状态
	const refreshing = ref(false);
	const list = reactive([]);
	// const mark = ref('deliveryAddress');
	const dialogshow = ref(false); //删除组件
	// const list = res([]);


	const params = ref({
		size: 10,
		pages: 1,
		userId: getUserid(),
		storeName: '',
	});


	const getdata = async (isRefresh = false) => {
		loading.value = false;
		try {
			// 防止重复请求
			if (loading.value && !isRefresh) return;
			// 重置错误状态
			error.value = false;
			// 设置加载状态
			loading.value = true;

			const response = await deviceStoresList(params.value);
			const records = response.data.records || [];
			// 新增：格式化时间
			const formattedRecords = records.map(item => ({
				...item,
				// 添加格式化后的时间字段（保留原始 createTime）
				createTime: formatISODate(item.createTime),
				updateTime: formatISODate(item.updateTime)
			}));
			// 如果是刷新操作，替换而不是追加数据
			if (isRefresh) {
				list.splice(0, list.length, ...formattedRecords);
			} else {
				list.push(...formattedRecords);
			}

			// 更新分页状态
			finished.value = records.length < params.value.size;
			params.value.pages += 1;
		} catch (err) {
			//console.error('获取数据失败', err);
			error.value = true;
			finished.value = false; // 确保可以重试

			// 如果是刷新操作需要保留刷新状态
			if (!isRefresh) {
				refreshing.value = false;
			}
		} finally {
			loading.value = false;
			// 如果是刷新操作，需要特殊处理
			if (isRefresh) {
				refreshing.value = false;
			}
		}
	};
	// 输入框搜索
	const handleSearch = (item) => {

		list.splice(0, list.length);
		// 重置分页参数
		params.value.pages = 1
		// 重置状态
		finished.value = false;
		loading.value = false;
		error.value = false;
		getdata(true);
	};
	// 下拉刷新处理
	const onRefresh = () => {
		// 立即清空列表
		list.splice(0, list.length);

		// 重置分页参数
		params.value = {
			size: 10,
			pages: 1,
			userId: getUserid(),
			storeName: '',
		};
		
		// 重置状态
		finished.value = false;
		loading.value = false;
		refreshing.value = true;
		error.value = false;

		// 直接调用 getdata，而不是等待列表自动触发
		getdata(true); // 传入 true 表示是刷新操作
	};
	// 删除
	const deletes = (item) => {

		const identity = getIdentity();
		if (identity == 0) {
			showToast('请先完成商户审核再删除店铺信息');
		} else if (identity == 1) {
			deleteParmams.value = {
				id: item.id,
				userId: getUserid()
			};
			dialogshow.value = true;
		} else if (identity == 2) {
			showToast('二级账号无删除店铺权限');
		}
	};
	const dialogConfirm = async () => {
		try {
			const response = await deleteStore(deleteParmams.value);
			if (response.status == 200) {
				showToast({
					type: 'success',
					message: '删除成功',
					forbidClick: true,
					duration: 1000
				});
			} else {
				showToast({
					type: 'fail',
					message: response.desc,
					forbidClick: true,
					duration: 1000
				});
			}
			setTimeout(() => {
				onRefresh();
			}, 1000)
		} catch (err) {
			showToast({
				type: 'fail',
				message: err.desc,
				forbidClick: true,
				duration: 1000
			});
		}
	};
	// 编辑
	const edit = (item) => {
		const identity = getIdentity();
		if (identity == 0) {
			showToast('请先完成商户审核再编辑店铺信息');
		} else if (identity == 1) {
			router.push({
				name: 'deliveryAddressEdit',
				params: {
					id: item.id,
					data: JSON.stringify(item)
				}
			})
		} else if (identity == 2) {
			showToast('二级账号无编辑店铺权限');
		}
	};
	//新增地址
	const addAddress = () => {
		const identity = getIdentity();
		if (identity == 0) {
			showToast('请先完成商户审核再新增店铺信息');
		} else if (identity == 1) {
			router.push({
				name: 'deliveryAddressEdit',
				params: {
					id: 'add',
					data: 'add'
				}
			})
		} else if (identity == 2) {
			showToast('二级账号无添加店铺权限');
		}
	};
	// 时间格式化工具函数
	const formatISODate = (isoString) => {
		// 修复格式问题：将 "+0000" 转成 "+00:00"
		if (!isoString) return "-"; // 处理空值
		try {
			const fixedDateString = isoString.replace(/(\+\d{2})(\d{2})$/, "$1:$2");
			const date = new Date(fixedDateString);
			// 转为本地时间并格式化为 "YYYY-MM-DD HH:mm:ss"
			return date.toLocaleString("zh-CN", {
				year: "numeric",
				month: "2-digit",
				day: "2-digit",
				hour: "2-digit",
				minute: "2-digit",
				second: "2-digit",
				hour12: false // 强制 24 小时制
			}).replace(/\//g, '-'); // 将斜杠替换为短横线（2025-02-23）
		} catch {
			return "-"; // 解析失败时返回占位符
		}
	};
</script>

<style lang="scss" scoped>
	.searchBox {
		background-color: #fff;
		width: 100%;

		.title {
			text-align: center;
			color: #000;
			padding: 0.5em;
			font-weight: bold;
		}
	}

	.footer {
		height: 54px;
		position: fixed;
		bottom: 50px;
		width: 100%;
		display: flex;
		justify-content: center;
		align-items: center;

		.addAddress {
			width: 80%;
			height: 42px;
			background-color: #00943B;
			color: #FFF;
			border: none;
			border-radius: 5px;
		}
	}

	.prompt {
		margin: 8px 0;
		text-align: center;
	}

	:deep(.searchBox) {
		.van-search {
			background-color: white;

			// 搜索框
			.van-search__content {
				background-color: white;
				border: 1px solid #cccccc;
				// border-radius: 5px;
				background-color: #f5f5f5;
			}
		}

		.van-search__action {
			color: #fff;
			background-color: #2FBC3C;
			border-radius: 16px;
			width: 40px;
			text-align: center;
			margin: 0 10px;
		}

		// 文字
		.search-confirm {
			display: flex;
			align-items: center;
			height: 100%;
			padding: 0 12px;

			.search-text {
				color: rgb(81, 164, 208);
				/* 蓝色搜索文字 */
				font-size: 14px;
				font-weight: 500;
				white-space: nowrap;
				cursor: pointer;
			}
		}
	}

	.flexbetween {
		display: flex;
		align-items: center;
		align-content: center;
		justify-content: space-between;
	}

	.grid-content {
		// border: 1px solid #c1c5cd;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		border-radius: 10px;
		margin-top: 20px;
		background-color: white;

		.margin-t-0 {
			margin-top: 0;
		}

		.margin-b-0 {
			margin-bottom: 0;
		}

		.margin-b-12 {
			margin-bottom: 12px;
		}

		.storeZi {
			color: rgb(147, 147, 147);
			width: 50%;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			font-size: 12px;
		}

		.storeTitle {
			font-size: 16px;
			width: 70%;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			color: #000;
		}

		.grid-content-bottom {
			display: flex;
			align-items: center;
			align-content: center;
			justify-content: space-around;
			padding: 0 50px;
			width: 100%;
			font-size: 12px;
			color: rgb(81, 164, 208);
			box-sizing: border-box;

			p {
				cursor: pointer;
			}
		}
	}

	.divider {
		width: 100%;
		height: 1px;
		border-bottom: 1px solid #c1c5cd;
	}
</style>